package com.example.logindesign;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	private ProgressDialog progressDialogWait;
	private Button loginButton;
	private EditText usernameEditText, passwordEditText;
	private CheckBox remeberBox;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String result = bundle.getString("result");
			if (result != null) {
				JSONArray jsonArray = null;
				try {
					jsonArray = new JSONArray(result);
					int len = jsonArray.length();
					JSONObject jsonObject = null;
					// 第一组数据表示的结果
					jsonObject = jsonArray.optJSONObject(0);
					// 返回结果json格式数据 Code=1 表示成功
					if (jsonObject.optString("Code").equals("1")) {
						// 从第二组开始取得有关数据
						jsonObject = jsonArray.optJSONObject(1);
						try {
							String userid = jsonObject.optString("userid");
							String username = jsonObject.optString("username");
							String unit = jsonObject.optString("unit");
							String unitcode = jsonObject.optString("unitcode");
							String bm = jsonObject.optString("bm");
							String password = passwordEditText.getText()
									.toString();
							boolean remeberme = remeberBox.isChecked();
							saveUserInfo(username, password, remeberme, userid,
									unit, unitcode, bm);
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("aaaaaaaa" + e.getMessage());
						}
						// 跳转
						Intent intent = new Intent();
						intent.setClass(LoginActivity.this, Mainmenu.class);
						startActivity(intent);
						LoginActivity.this.finish();
					} else {
						// 登录失败
						Toast toast = Toast.makeText(LoginActivity.this,
								"用户名或密码错误", Toast.LENGTH_LONG);
						// toast.setGravity(Gravity.CENTER, 0, 0);// 放在中间显示
						toast.show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏注意这句一定要写在setContentView()方法的前面，不然会报错的
		setContentView(R.layout.login);

		loginButton = (Button) findViewById(R.id.login);
		usernameEditText = (EditText) findViewById(R.id.username);
		passwordEditText = (EditText) findViewById(R.id.password);
		remeberBox = (CheckBox) findViewById(R.id.remeber);

		// 用户名和密码初始化
		initUserInfo();
		loginButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String username = usernameEditText.getText().toString();
				String password = passwordEditText.getText().toString();

				if (!username.equals("") && !password.equals("")) {
					// 弹出登录等待窗口
					progressDialogWait = ProgressDialog.show(
							LoginActivity.this, "提示", "登录中,请稍等......");
					// 连接webservice 判断登录结果
					new Thread(runnable).start();
				}
			}
		});
	}

	/**
	 * 对话框
	 */
	private void alertDialog() {
		// 1 创建一个Builder
		AlertDialog.Builder builder = new Builder(LoginActivity.this);
		// 2 给Builder设置属性
		builder.setMessage("确定退出吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// MainActivity.this.finish();
				// System.exit(0);
				dialog.dismiss();
			}
		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		// 3 创建Dialog
		AlertDialog alertDialog = builder.create();
		// 4 显示Dialog
		alertDialog.show();
	}

	/**
	 * 用户名密码选择框初始化
	 */
	private void initUserInfo() {
		// TODO Auto-generated method stub
		SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",
				Activity.MODE_PRIVATE);
		if (sharedPreferences.getBoolean("remeberme", false)) {
			remeberBox.setChecked(true);
			usernameEditText.setText(sharedPreferences
					.getString("username", ""));
			passwordEditText.setText(sharedPreferences
					.getString("password", ""));
		}
	}

	/**
	 * 存储用户信息到sharedpreferences中
	 * 
	 * @param userInfo
	 */
	private void saveUserInfo(String username, String password,
			Boolean remeberme, String userid, String unit, String unitcode,
			String bm) {
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"UserInfo", LoginActivity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPreferences.edit();
		// 获取要保持信息，进行存储
		editor.putString("username", username);
		editor.putString("password", password);
		editor.putBoolean("remeberme", remeberme);
		editor.putString("userid", userid);
		editor.putString("unit", unit);
		editor.putString("unitcode", unitcode);
		editor.putString("bm", bm);
		// 提交事务
		editor.commit();
	}

	Runnable runnable = new Runnable() {

		public void run() {
			Log.e(null, Thread.currentThread().getName() + "登录线程");
			String namespace = "http://tempuri.org/";
			String methodName = "user_login";
			String endPoint = "http://192.168.1.198:1536/CommunitySystemsicWsWF.asmx";
			String soapAcion = "http://tempuri.org/user_login";
			SoapObject soapObject = new SoapObject(namespace, methodName);

			soapObject.addProperty("name", usernameEditText.getText()
					.toString());
			soapObject.addProperty("password", passwordEditText.getText()
					.toString());

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.setOutputSoapObject(soapObject);
			envelope.dotNet = true;
			HttpTransportSE transportSE = new HttpTransportSE(endPoint);
			try {
				transportSE.call(soapAcion, envelope);
				if (envelope.getResponse() != null) {
					SoapObject object = (SoapObject) envelope.bodyIn;
					String result = object.getProperty(0).toString();
					// 登录成功
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("result", result);
					msg.setData(bundle);
					handler.sendMessage(msg);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				// 关闭ProgressDialog 要放到这里吗？
				progressDialogWait.dismiss();
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
